package com.forester.foresterplatform.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.forester.foresterplatform.system.entity.*;
import com.forester.foresterplatform.system.mapper.PermissionMapper;
import com.forester.foresterplatform.system.mapper.RolePermissionMapper;
import com.forester.foresterplatform.system.mapper.UserMapper;
import com.forester.foresterplatform.system.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据 username 查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if(Objects.isNull(user)) {
            log.info("登录失败");
            throw new RuntimeException("用户名 或 密码错误"); // security 的过滤器链会处理异常
        }

        // 查询用户权限
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getId()));
        if(userRoles.isEmpty())  // 用户没有分配角色
            return user;
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new LambdaQueryWrapper<RolePermission>().in(RolePermission::getRoleId, roleIds));
        if(rolePermissions.isEmpty())  // 用户分配的角色均未设置权限
            return user;
        List<Long> permissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<Permission> permissions = permissionMapper.selectList(new LambdaQueryWrapper<Permission>().in(Permission::getId, permissionIds));
        List<String> permissionStrings = permissions.stream().map(Permission::getName).collect(Collectors.toList());

        // 封装成 UserDetails
        user.setPermissionsStrings(permissionStrings);

        return user;
    }
}
